import os
import pandas as pd
import matplotlib.pyplot as plt

# --- 文件路径与输出目录 ---
file_path = r'/database/private/mgcdb/info_xml_raw_match_1.csv'
output_dir = r'/database/home/duansizhang/hrv_predict/result/pic'
os.makedirs(output_dir, exist_ok=True)

# --- 读取数据 ---
data = pd.read_csv(file_path, dtype={'userid': str, 'recordid': str})

# --- Gender distribution ---
gender_counts = data['Gender'].value_counts()
male_count = gender_counts.get('男', 0)
female_count = gender_counts.get('女', 0)
print(f"Male count: {male_count}, Female count: {female_count}")

# --- Age validation ---
data['age'] = pd.to_numeric(data['age'], errors='coerce')
invalid_age = data[(data['age'] < 0) | (data['age'] > 100)]
if not invalid_age.empty:
    print(f"Found {invalid_age.shape[0]} records with age outside 0–100:")
    print(invalid_age[['userid', 'age']])
else:
    print("No age data outside 0–100 range found.")
data = data[(data['age'] >= 0) & (data['age'] <= 100)]

# --- Plotting: combined figure ---
fig, axes = plt.subplots(1, 2, figsize=(16, 8))

# Gender bar chart
gender_counts.plot(
    kind='bar',
    ax=axes[0]
)
axes[0].set_title('Gender Distribution', fontsize=16)
axes[0].set_xlabel('Gender', fontsize=14)
axes[0].set_ylabel('Count', fontsize=14)
axes[0].set_xticklabels(['Male' if g=='男' else 'Female' for g in gender_counts.index], rotation=0)

# Age histogram
axes[1].hist(
    data['age'],
    bins=range(0, 101, 5),
    edgecolor='black',
    align='left'
)
axes[1].set_title('Age Distribution', fontsize=16)
axes[1].set_xlabel('Age (years)', fontsize=14)
axes[1].set_ylabel('Count', fontsize=14)
axes[1].set_xlim(0, 100)
axes[1].set_xticks(range(0, 101, 5))

plt.tight_layout()
combined_path = os.path.join(output_dir, 'gender_age_distribution.png')
plt.savefig(combined_path)
plt.close()

print(f"Combined figure saved to: {combined_path}")
